//
//  PerfessionCertV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/9.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "PerfessionCertV2ViewController.h"

#import <PYPhotoBrowser/PYPhotoBrowser.h>
#import <PYPhotoBrowser/PYPhotosPreviewController.h>
#import <TZImagePickerController/TZImagePickerController.h>

@interface PerfessionCertV2ViewController () <PYPhotosViewDelegate, TZImagePickerControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) PerfessionCertV2ViewModel* viewModel;

// UI
//@property (weak, nonatomic) UILabel *addressLabel;

//IBOutlet
@property (nonatomic, weak) IBOutlet UIView* introTextView;
@property (nonatomic, weak) IBOutlet UITextField* nameTF;
@property (nonatomic, weak) IBOutlet UITextField* mobileTF;
@property (nonatomic, weak) IBOutlet UIView* uploadPersoncertContentView;
@property (nonatomic, weak) IBOutlet UIView* uploadAboutContentView;
@property (nonatomic, weak) IBOutlet UIButton* submitBtn;

@end

@implementation PerfessionCertV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
         self.view.backgroundColor = MHGlobalGrayBackgroundColor;
     }];
}

- (void)initUI
{
    @weakify(self);
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* willDisAppearSignal = [[self rac_signalForSelector:@selector(viewWillDisappear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [willDisAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:[didAppearSignal replay]] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         if (self.viewModel.isReload)
         {
             [self.viewModel.reloadCmd execute:nil];
         }
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
//    RAC(self.viewModel, strName) = [[self.nameTF rac_textSignal] distinctUntilChanged];
//    RAC(self.viewModel, strMobile) = [[self.mobileTF rac_textSignal] distinctUntilChanged];
    RACChannelTo(self.viewModel, strName) = RACChannelTo(self.nameTF, text);
    RACChannelTo(self.viewModel, strMobile) = RACChannelTo(self.mobileTF, text);
    
    UIView* upload1InputView = [self.uploadPersoncertContentView viewWithTag:1010];
    UIView* upload2InputView = [self.uploadAboutContentView viewWithTag:1020];
    
    [RACObserve(self.viewModel, personCertImages) subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSMutableArray* epUIImageDatas = x;
         
         NSMutableArray* images = [NSMutableArray array];
         for (NSInteger index=0; index<epUIImageDatas.count; index++)
         {
             EPUIImageData* curUIImageData = epUIImageDatas[index];
             
             [images addObject:curUIImageData.img];
         }
         
         PYPhotosView* photosView = [upload1InputView viewWithTag:2000];
         if (photosView != nil)
         {
             photosView.images = images;
         }
         
         NSInteger imgCount = [images count] + 1;
         imgCount = imgCount>9?9:imgCount;
         NSInteger imgColNum = 3;
         CGFloat imgOffset = 16;
         CGFloat imgSize = (upload1InputView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
         
         NSInteger row = imgCount/3 + (imgCount%3>0?1:0);
         CGFloat viewHeight = imgSize*row + imgOffset*(row - 1);
         //修改约束
         for (NSLayoutConstraint* curConstraint in self.uploadPersoncertContentView.constraints)
         {
             if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
             {
                 curConstraint.constant = viewHeight + 8.0f*2.0f + 12.0f + 18.0f;
                 break;
             }
         }
     }];
    
    [RACObserve(self.viewModel, aboutCertImages) subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSMutableArray* epUIImageDatas = x;
         
         NSMutableArray* images = [NSMutableArray array];
         for (NSInteger index=0; index<epUIImageDatas.count; index++)
         {
             EPUIImageData* curUIImageData = epUIImageDatas[index];
             
             [images addObject:curUIImageData.img];
         }
         
         PYPhotosView* photosView = [upload2InputView viewWithTag:2001];
         if (photosView != nil)
         {
             photosView.images = images;
         }
         
         NSInteger imgCount = [images count] + 1;
         imgCount = imgCount>9?9:imgCount;
         NSInteger imgColNum = 3;
         CGFloat imgOffset = 16;
         CGFloat imgSize = (upload2InputView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
         
         NSInteger row = imgCount/3 + (imgCount%3>0?1:0);
         CGFloat viewHeight = imgSize*row + imgOffset*(row - 1);
         //修改约束
         for (NSLayoutConstraint* curConstraint in self.uploadAboutContentView.constraints)
         {
             if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
             {
                 curConstraint.constant = viewHeight + 8.0f*2.0f + 12.0f + 18.0f;
                 break;
             }
         }
     }];
    
    self.viewModel.showImgPickerCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                                       {
                                           @strongify(self)
                                           
                                           [self showImgPicker];
                                           
                                           return [RACSignal empty];
                                       }];
    
    [[self rac_signalForSelector:@selector(photosView:didAddImageClickedWithImages:) fromProtocol:@protocol(PYPhotosViewDelegate)] subscribeNext:^(id x)
     {
         @strongify(self)
         
         RACTuple* tuple = x;
         PYPhotosView* curPView = tuple.first;
         
         self.viewModel.ctrlTag = curPView.tag;
         
         [self.viewModel.showImgPickerCmd execute:nil];
     }];
    
    [[self rac_signalForSelector:@selector(photosView:didDeleteImageIndex:) fromProtocol:@protocol(PYPhotosViewDelegate)] subscribeNext:^(id x)
     {
         @strongify(self);
         
         RACTuple* tuple = x;
         PYPhotosView* curPView = tuple.first;
         
         self.viewModel.ctrlTag = curPView.tag;
         
         NSNumber* delImgIndexValue = tuple.second;
         
         if (self.viewModel.isInPreview)
         {
             [self.viewModel.waitDelIndexes addObject:delImgIndexValue];
         }
         else
         {
             [self.viewModel.deleteImgCmd execute:delImgIndexValue];
         }
     }];
    
    [[self rac_signalForSelector:@selector(photosView:didPreviewImagesWithPreviewControlelr:) fromProtocol:@protocol(PYPhotosViewDelegate)] subscribeNext:^(id x)
    {
        @strongify(self);
        
        RACTuple* tuple = x;
        
        PYPhotosView* photosView = tuple.first;
        PYPhotosPreviewController* previewController = tuple.second;
        
        self.viewModel.ctrlTag = photosView.tag;
        
        @weakify(self);
        [self _buildPreviewContact:previewController];
        
        self.viewModel.isInPreview = YES;
    }];
    
    // TZ图片选择回调
    RACSignal* tzChooseImagePickerSignal = [[self rac_signalForSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:) fromProtocol:@protocol(TZImagePickerControllerDelegate)] replay];
    [tzChooseImagePickerSignal subscribeNext:^(id x)
     {
         @strongify(self);
         
         RACTuple* tuple = x;
         
         NSArray* photos = tuple.second;
         
         [self.viewModel.addImgCmd execute:photos];
     }];
    
    // 图片选择回调
    RACSignal* chooseImagePickerSignal = [[self rac_signalForSelector:@selector(imagePickerController:didFinishPickingMediaWithInfo:) fromProtocol:@protocol(UIImagePickerControllerDelegate)] replay];
    
    [chooseImagePickerSignal subscribeNext:^(id x) {
        @strongify(self)
        
        RACTuple* tuple = x;
        
        UIImagePickerController* picker = tuple.first;
        NSDictionary* info = tuple.second;
        
        // 从info中将图片取出，并加载到imageView当中
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        [self.viewModel.addImgCmd execute:@[image]];
        
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    [[self rac_signalForSelector:@selector(imagePickerControllerDidCancel:) fromProtocol:@protocol(UIImagePickerControllerDelegate)] subscribeNext:^(id x) {
        @strongify(self)
        
        RACTuple* tuple = x;
        
        UIImagePickerController* pickerC = tuple.first;
        
        [pickerC dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
}

- (void)_setupAllView
{
    @weakify(self);
    
    //专家简介
    UIView* introInputView = self.introTextView;
    YYTextView* addrTView = [[YYTextView alloc] initWithFrame:(CGRect) {0, 0, introInputView.frame.size}];
    addrTView.font = [UIFont systemFontOfSize:16.0f];
    addrTView.placeholderFont = [UIFont systemFontOfSize:16.0f];
    addrTView.placeholderText = @"填写专家简介";
    addrTView.placeholderTextColor = UIColorHex(#f2f2f2);
    addrTView.tag = 1000;
    [introInputView addSubview:addrTView];
    RACChannelTo(self.viewModel, strIntro) = RACChannelTo(addrTView, text);
    
    UIView* upload1InputView = [self.uploadPersoncertContentView viewWithTag:1010];
    {
        // 图片添加器
        [upload1InputView removeAllSubviews];
        {
            NSInteger imgColNum = 3;
            
            // 计算大小
            CGFloat imgOffset = 16;
            CGFloat imgSize = (upload1InputView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
            
            NSMutableArray* imgs = [NSMutableArray array];
            PYPhotosView *photosView = [PYPhotosView photosViewWithImages:imgs];
            photosView.photosState = PYPhotosViewStateWillCompose;
            photosView.photosMaxCol = 3;
            photosView.imagesMaxCountWhenWillCompose = 9;
            photosView.autoLayoutWithWeChatSytle = NO;
            photosView.oneImageFullFrame = NO;
            photosView.photoWidth = imgSize;
            photosView.photoHeight = imgSize;
            photosView.photoMargin = imgOffset;
            photosView.delegate = self;
            
            NSInteger row = 1;
            photosView.frame = (CGRect) {0, 0, upload1InputView.frame.size.width, imgSize*row + imgOffset*(row - 1)};
            photosView.tag = 2000;
            [upload1InputView addSubview:photosView];
            //修改约束
            for (NSLayoutConstraint* curConstraint in self.uploadPersoncertContentView.constraints)
            {
                if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
                {
                    curConstraint.constant = photosView.frame.size.height + 8.0f*2.0f + 12.0f + 18.0f;
                    
                    break;
                }
            }
        }
    }
    
    UIView* upload2InputView = [self.uploadAboutContentView viewWithTag:1020];
    {
        // 图片添加器
        [upload2InputView removeAllSubviews];
        {
            NSInteger imgColNum = 3;
            
            // 计算大小
            CGFloat imgOffset = 16;
            CGFloat imgSize = (upload2InputView.frame.size.width - ((imgColNum + 1)*imgOffset)) / imgColNum;
            
            NSMutableArray* imgs = [NSMutableArray array];
            PYPhotosView *photosView = [PYPhotosView photosViewWithImages:imgs];
            photosView.photosState = PYPhotosViewStateWillCompose;
            photosView.photosMaxCol = 3;
            photosView.imagesMaxCountWhenWillCompose = 9;
            photosView.autoLayoutWithWeChatSytle = NO;
            photosView.oneImageFullFrame = NO;
            photosView.photoWidth = imgSize;
            photosView.photoHeight = imgSize;
            photosView.photoMargin = imgOffset;
            photosView.delegate = self;
            
            NSInteger row = 1;
            photosView.frame = (CGRect) {0, 0, upload2InputView.frame.size.width, imgSize*row + imgOffset*(row - 1)};
            photosView.tag = 2001;
            [upload2InputView addSubview:photosView];
            //修改约束
            for (NSLayoutConstraint* curConstraint in self.uploadAboutContentView.constraints)
            {
                if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
                {
                    curConstraint.constant = photosView.frame.size.height + 8.0f*2.0f + 12.0f + 18.0f;
                    
                    break;
                }
            }
        }
    }
    
    [[self.submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self.view resignFirstResponder];
         
         [MBProgressHUD mh_showProgressHUD:@"提交中..."];
         
         //             self.viewModel.stepIndex = 2;
         [self.viewModel.submitCmd execute:nil];
     }];
    [[self.viewModel.submitCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        [MBProgressHUD mh_hideHUD];
        
        [self.navigationController popViewControllerAnimated:YES];
        
        [MBProgressHUD mh_showTips:x];
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        [um updateUserInfo];
    }];
    [[self.viewModel.submitCmd.errors deliverOnMainThread] subscribeNext:^(NSError* error)
    {
        [MBProgressHUD mh_hideHUD];
        
        /// 处理验证错误的error
        if ([error.domain isEqualToString:SUCommandErrorDomain])
        {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return ;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
}

#pragma mark - 功能
- (void)_buildPreviewContact:(PYPhotosPreviewController*)pC
{
    @weakify(self);
    [[[pC rac_signalForSelector:@selector(viewWillDisappear:)] takeUntil:[pC rac_willDeallocSignal]] subscribeNext:^(id x)
     {
         @strongify(self);
         
         self.viewModel.isInPreview = NO;
         
         [self.viewModel.deleteImgsCmd execute:nil];
     }];
}

- (void)showImgPicker
{
    // 创建UIImagePickerController实例
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    // 设置代理
    imagePickerController.delegate = self;
    // 是否允许编辑（默认为NO）
    imagePickerController.allowsEditing = NO;
    
    // 创建一个警告控制器
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 设置警告响应事件
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 设置照片来源为相机
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        // 设置进入相机时使用前置或后置摄像头
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        
        // 展示选取照片控制器
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }];
    
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //MaxImagesCount  可以选着的最大条目数
        NSInteger maxCount = 0;
        if (self.viewModel.ctrlTag == 2000)
        {
            maxCount = 9 - self.viewModel.personCertImages.count;
        }
        else if (self.viewModel.ctrlTag == 2001)
        {
            maxCount = 9 - self.viewModel.aboutCertImages.count;
        }
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCount delegate:self];
        imagePicker.navigationBar.tintColor = UIColorHex(#000000);
        [imagePicker setBarItemTextColor:UIColorHex(#000000)];
        
        // 是否显示可选原图按钮
        imagePicker.allowPickingOriginalPhoto = NO;
        // 是否允许显示视频
        imagePicker.allowPickingVideo = NO;
        // 是否允许显示图片
        imagePicker.allowPickingImage = YES;
        
        // 这是一个navigation 只能present
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        // 添加警告按钮
        [alert addAction:cameraAction];
    }
    
    [alert addAction:photosAction];
    [alert addAction:cancelAction];
    
    alert.popoverPresentationController.sourceView = self.view;
    alert.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
    
    // 展示警告控制器
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 跳转

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
